package com.quick.util;

import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.quick.Quick;
import com.quick.config.QuickProperties;
import com.quick.config.QuickSystem;
import com.quick.config.TokenStorage;
import com.quick.exception.QuickStateEnum;
import com.quick.spring.SpringUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.Map;
@Slf4j
@SuppressWarnings("unchecked")
public class TokenUtil {
    public static final String CHARACTER_SET = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";

    public static String generateKey() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 30; i++) {
            int randomInt = new SecureRandom().nextInt(CHARACTER_SET.length());
            sb.append(CHARACTER_SET.substring(randomInt, randomInt + 1));
        }
        return sb.toString();
    }

    public static String getToken(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            log.info("name:{},value:{}",name,value);
        }
        return request.getHeader("x-token");
    }

    public static void main(String[] args) {
        int le = 10;
        for (int i = 1; i <= le; i++) {
            DecimalFormat df = new DecimalFormat("#.##########%");
            BigDecimal b = new BigDecimal((double)i/(double)le);
            System.out.println(".halve-"+le+" .col-"+i+"{width:"+df.format(b)+";}");
        }
    }

	public static boolean check(String token) {
		Quick  quick = SpringUtil.getBean(Quick.class);
		Map<String, Object> develop = quick.getDevelop();
		QuickProperties basis = (QuickProperties) develop.get("basis");
		if(basis.getTokenStorage() == TokenStorage.LOCAL) {
			Object loginUser =  QuickTool.getRequest().getSession().getAttribute(QuickTool.getTokenKey());
			QuickTool.isNull(loginUser, QuickStateEnum.TOKEN_FAILURE);
			return true;
		}
		RedisTemplate<Object, ?>  redisTemplate = (RedisTemplate<Object, ?>) SpringUtil.getBean("redisTemplate");
		String uuid = QuickSystem.getKey(token);
		Boolean flag = redisTemplate.hasKey(uuid);
		QuickTool.isFalse(flag, QuickStateEnum.TOKEN_FAILURE);
		return flag;
	}
}
